<template>
  <div class="building-management">
    <!-- 权限说明提示 -->
    <!-- <el-alert
      v-if="showPermissionTip"
      :title="`当前权限：${getDataScopeTextComputed}`"
      :description="getDataScopeDescriptionComputed"
      :type="getDataScopeTagTypeComputed as any"
      show-icon
      :closable="false"
      style="margin-bottom: 16px"
    /> -->

    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="queryForm" inline>
        <el-form-item label="楼栋名称">
          <el-input v-model="queryForm.buildingName" placeholder="请输入楼栋名称" clearable />
        </el-form-item>
        <el-form-item label="楼栋编号">
          <el-input v-model="queryForm.buildingNo" placeholder="请输入楼栋编号" clearable />
        </el-form-item>
        <el-form-item label="所属社区">
          <el-select v-model="queryForm.communityId" placeholder="请选择社区" clearable>
            <el-option 
              v-for="community in validCommunityList" 
              :key="community.id"
              :label="community.communityName" 
              :value="community.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
            <el-option :label="STATUS.ENABLED" :value="1" />
            <el-option :label="STATUS.DISABLED" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 楼栋列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>楼栋列表</span>
          <div class="header-actions">
            <el-button 
              type="primary" 
              :icon="Plus" 
              @click="handleAdd"
            >
              新增楼栋
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 空状态 -->
      <el-empty 
        v-if="showEmptyState" 
        :description="emptyStateDescription"
        :image-size="200"
      >
        <template #extra>
          <el-button 
            type="primary" 
            :icon="Plus" 
            @click="handleAdd"
          >
            新增楼栋
          </el-button>
        </template>
      </el-empty>
      
      <!-- 数据表格 -->
      <el-table 
        v-else
        :data="filteredBuildingList" 
        :loading="buildingLoading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="buildingName" label="楼栋名称" min-width="120" />
        <el-table-column prop="buildingNo" label="楼栋编号" min-width="120" />
        <el-table-column prop="communityName" label="所属社区" min-width="150" />
        <el-table-column prop="floorCount" label="楼层数" width="80" />
        <el-table-column prop="unitCount" label="单元数" width="80" />
        <el-table-column prop="unitsPerFloor" label="每层户数" width="100" />
        <el-table-column prop="householdCount" label="房户数" width="80" />
        <el-table-column label="入住率" width="100">
          <template #default="{ row }">
            <el-progress 
              :percentage="calculateOccupancyRate(row)" 
              :color="getOccupancyColor(row)"
              :show-text="false"
            />
            <span class="occupancy-text">{{ calculateOccupancyRate(row) }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'error'">
              {{ row.status === 1 ? STATUS.ENABLED : STATUS.DISABLED }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              @click="handleViewLayout(row)"
            >
              布局
            </el-button>
            <el-button 
              v-if="canManage" 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="!showEmptyState">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 楼栋表单对话框 -->
    <BuildingForm
      v-model:visible="formVisible"
      :building="currentBuilding"
      :community-list="filteredCommunityList"
      @success="handleFormSuccess"
    />
    

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { STATUS } from '@/constants/status'
import { Plus, Message } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useRegionStore } from '@/store/region'
import { useUserStore } from '@/store/user'
import { ROLE_CODES } from '@/constants/roles'
import { getDataScopeText, getDataScopeDescription, getDataScopeTagType } from '@/utils/permission'
import { showInfo, showError, showSuccess } from '@/utils/message'

import BuildingForm from './BuildingForm.vue'
import { buildingApi } from '@/api/building'

// 组件引用
const regionStore = useRegionStore()
const userStore = useUserStore()
const router = useRouter()

// 初始化权限信息，防止未定义报错
const userPermissionInfo = ref({
  isSuperAdmin: false,
  hasPropertyCompany: false,
  propertyCompanyId: null as number | null,
  propertyCompanyName: ''
})

// 加载用户权限信息
const loadUserPermissionInfo = async () => {
  try {
    // 首先确保公司信息是最新的
    await userStore.checkAndUpdateCompanyInfo()
    
    const permission = await userStore.getUserDataScope()
    userPermissionInfo.value.isSuperAdmin = permission.isSuperAdmin
    userPermissionInfo.value.hasPropertyCompany = permission.hasPropertyCompany
    userPermissionInfo.value.propertyCompanyId = permission.companyId
    userPermissionInfo.value.propertyCompanyName = permission.companyName
  } catch (error) {
    userPermissionInfo.value.isSuperAdmin = false
    userPermissionInfo.value.hasPropertyCompany = false
    userPermissionInfo.value.propertyCompanyId = null
    userPermissionInfo.value.propertyCompanyName = ''
  }
}

// 权限判断computed
const isSuperAdmin = computed(() => {
  return userPermissionInfo.value.isSuperAdmin
})

const hasPropertyCompany = computed(() => {
  return userPermissionInfo.value.hasPropertyCompany
})

const canManage = computed(() => isSuperAdmin.value || hasPropertyCompany.value)

// 获取用户数据权限范围
const getUserDataScope = () => {
  if (isSuperAdmin.value) {
    return 'ALL'
  }
  // 这里可以根据用户权限返回具体的权限范围
  return ROLE_CODES.PROPERTY_ADMIN
}

// 获取数据权限范围文本
const getDataScopeTextComputed = computed(() => {
  // 兜底：如userInfo或dataScope不存在，返回['ALL']
  const dataScope = (userStore.userInfo && Array.isArray((userStore.userInfo as any).dataScope))
    ? (userStore.userInfo as any).dataScope as string[]
    : ['ALL']
  return getDataScopeText(dataScope)
})

// 获取数据权限范围描述
const getDataScopeDescriptionComputed = computed(() => {
  // 兜底：如userInfo或dataScope不存在，返回['ALL']
  const dataScope = (userStore.userInfo && Array.isArray((userStore.userInfo as any).dataScope))
    ? (userStore.userInfo as any).dataScope as string[]
    : ['ALL']
  return getDataScopeDescription(dataScope)
})

// 获取数据权限范围标签类型
const getDataScopeTagTypeComputed = computed(() => {
  // 兜底：如userInfo或dataScope不存在，返回['ALL']
  const dataScope = (userStore.userInfo && Array.isArray((userStore.userInfo as any).dataScope))
    ? (userStore.userInfo as any).dataScope as string[]
    : ['ALL']
  return getDataScopeTagType(dataScope) as any
})

// 响应式数据
const queryForm = reactive({
  buildingName: '',
  buildingNo: '',
  communityId: undefined as number | undefined,
  status: undefined as number | undefined
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const formVisible = ref(false)
const currentBuilding = ref<any>(null)

// 计算属性 - 确保返回数组格式
const buildingPage = ref<{ records: any[]; total: number }>({ records: [], total: 0 })
const buildingList = computed(() => {
  return Array.isArray(buildingPage.value.records) ? buildingPage.value.records : []
})

const buildingLoading = computed(() => regionStore.buildingLoading)

const communityList = computed(() => {
  const list = regionStore.communityList
  return Array.isArray(list) ? list : []
})

// 根据权限过滤的社区列表
const filteredCommunityList = computed((): any[] => {
  return Array.isArray(communityList.value) ? communityList.value : []
})

// 有效的社区列表（过滤掉无效数据）
const validCommunityList = computed((): any[] => {
  return filteredCommunityList.value.filter(community => 
    community && community.id && community.communityName
  )
})

// 根据权限过滤的楼栋列表
const filteredBuildingList = computed((): any[] => {
  return Array.isArray(buildingList.value) ? buildingList.value : []
})

// 权限提示相关计算属性
const showPermissionTip = computed(() => {
  return !isSuperAdmin.value
})

const showEmptyState = computed(() => {
  return !isSuperAdmin.value && (!filteredBuildingList.value || filteredBuildingList.value.length === 0)
})

const emptyStateMessage = computed(() => {
  if (isSuperAdmin.value) {
    return '暂无楼栋数据'
  }
  return '暂无权限访问楼栋数据'
})

const emptyStateDescription = computed(() => {
  if (isSuperAdmin.value) {
    return '当前没有楼栋数据，您可以点击下方按钮新增楼栋'
  }
  return '您没有访问楼栋数据的权限，请联系管理员为您分配相应的物业公司'
})

// 计算入住率
const calculateOccupancyRate = (row: any) => {
  if (!row.householdCount || !row.totalHouseholds) {
    return 0
  }
  return Math.round((row.householdCount / row.totalHouseholds) * 100)
}

// 获取入住率颜色
const getOccupancyColor = (row: any) => {
  const rate = calculateOccupancyRate(row)
  if (rate >= 80) return '#67C23A'
  if (rate >= 60) return '#E6A23C'
  if (rate >= 40) return '#F56C6C'
  return '#909399'
}

// 联系管理员
const handleContactAdmin = () => {
  showInfo('请联系系统管理员为您分配相应的权限')
}

// 查询楼栋列表
const loadBuildingList = async () => {
  try {
    const params = {
      ...queryForm,
      pageNum: pagination.current,
      pageSize: pagination.size
    }
    const result = await regionStore.getBuildingList(params)
    buildingPage.value = result
    pagination.total = result.total || 0
  } catch (error) {
    showError('加载楼栋列表失败')
  }
}

// 查询
const handleSearch = () => {
  pagination.current = 1
  loadBuildingList()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    buildingName: '',
    buildingNo: '',
    communityId: undefined,
    status: undefined
  })
  pagination.current = 1
  loadBuildingList()
}

// 新增楼栋
const handleAdd = () => {
  currentBuilding.value = null
  formVisible.value = true
}

// 编辑楼栋
const handleEdit = async (row: any) => {
  try {
    // 先获取完整的楼栋详情数据
    const response = await buildingApi.getBuildingDetail(row.id)
    if (response.data) {
      currentBuilding.value = response.data
    } else {
      // 如果获取详情失败，使用列表数据
      currentBuilding.value = { ...row }
    }
    formVisible.value = true
  } catch (error) {
    console.error('获取楼栋详情失败:', error)
    // 获取详情失败时，使用列表数据
    currentBuilding.value = { ...row }
    formVisible.value = true
  }
}

// 查看楼栋布局
const handleViewLayout = (row: any) => {
  // 跳转到楼栋布局页面
  router.push(`/region/building/layout/${row.id}`)
}

// 删除楼栋
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除楼栋"${row.buildingName}"吗？删除后不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await regionStore.deleteBuilding(row.id)
    showSuccess('删除成功')
    loadBuildingList()
  } catch (error) {
    if (error !== 'cancel') {
      showError('删除失败')
    }
  }
}



// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadBuildingList()
}

// 当前页改变
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadBuildingList()
}

// 表单提交成功
const handleFormSuccess = () => {
  formVisible.value = false
  loadBuildingList()
}



// 初始化数据
const initData = async () => {
  try {
    // 1. 首先加载用户权限信息
    await loadUserPermissionInfo();
    // 2. 获取当前用户的物业公司ID（如有）
    let communityParams: any = {};
    if (isSuperAdmin.value) {
      // 超级管理员不过滤
      communityParams = {};
    } else if (hasPropertyCompany.value && userPermissionInfo.value.propertyCompanyId) {
      // 物业公司用户按公司过滤
      communityParams = { propertyCompanyId: String(userPermissionInfo.value.propertyCompanyId) };
    }
    // 3. 并行加载业务数据
    await Promise.all([
      regionStore.getCommunityList(communityParams), // 社区列表 - 只调用一次
      loadBuildingList() // 楼栋列表
    ]);
  } catch (error) {
    console.error('初始化数据失败:', error);
    ElMessage.error({ message: '初始化数据失败', type: 'error' });
  }
};

// 组件挂载时初始化
onMounted(() => {
  initData();
});
</script>

<style lang="scss" scoped>
.building-management {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 8px;
      }
    }
    
    .occupancy-text {
      margin-left: 8px;
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
    
    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}
</style> 